package bjfuwjx.exp4;

import java.util.Comparator;
import java.util.concurrent.CopyOnWriteArrayList;

import static bjfuwjx.exp4.RedFlag.CountNum;
import static bjfuwjx.exp4.RedFlag.cnt;

public class ShootingBallThread extends Thread implements Runnable {
    public ShootingBall ball;
    public MyPanel ballPanel;
    public CopyOnWriteArrayList<Ball> list1,list2;
    public boolean IsStop = true;
    public ShootingBallThread(ShootingBall ball,MyPanel ballPanel,CopyOnWriteArrayList<Ball> list1,CopyOnWriteArrayList<Ball> list2) {
        this.ball=ball;
        this.ballPanel=ballPanel;
        this.list1=list1;
        this.list2=list2;
    }
    public void Goal(CopyOnWriteArrayList<Ball> list1,CopyOnWriteArrayList<Ball> list2,ShootingBall ball) {
        CopyOnWriteArrayList<Ball> list=new CopyOnWriteArrayList<>();
        for (Ball b:list1){
            if (b.x<=450&&b.x>=410){
                if (b.y<=ball.y&&b.y>=ball.y-40)
                    list.add(b);
            }
        }
        for (Ball b:list2){
            if (b.x<=450&&b.x>=410){
                if (b.y<=ball.y&&b.y>=ball.y-40)
                    list.add(b);
            }
        }
        list.sort(new Comparator<Ball>() {
            @Override
            public int compare(Ball o1, Ball o2) {
                if (o1.y>o2.y){
                    return 1;
                }
                else if (o1.y==o2.y){
                    return 0;
                }
                else
                    return -1;
            }
        });
        if (list.size()!=0){
            if (list.get(0).radius!=0) {
                ball.y=-21.0;
                ball.radius=0.0;
                list.get(0).x=1200.0;
                list.get(0).radius=0.0;
                CountNum++;
            }
        }
    }
    @Override
    public void run() {
        while (ball.y>=-20) {
            if (!IsStop) {
                ball.move();
                Goal(list1,list2,ball);
                ballPanel.repaint();
            }
            try {
                Thread.sleep(2);
            }catch (Exception e){}
        }
        cnt++;
    }
}
